package com.carrot.auth.holder;

import com.carrot.auth.entity.LoginUserInfo;

import java.util.Optional;

/**
 * 用户上下文
 *
 * @author liuhongzhen
 */
public final class UserContextHolder {

    /**
     * 存储用户上下文信息
     */
    public static final ThreadLocal<LoginUserInfo> THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 获取当前上下文用户
     * 推荐用法,避免空指针:
     * LoginUserInfo loginUserInfo = UserContextHolder.get().orElseThrow(() -> new BusinessException("提示未登录即可"));
     *
     * @return Optional<LoginUserInfo>
     */
    public static Optional<LoginUserInfo> getCurrUser() {
        return Optional.ofNullable(THREAD_LOCAL.get());
    }


    public static void setCurrUser(LoginUserInfo loginUserInfo) {
        if (THREAD_LOCAL.get() == null) {
            THREAD_LOCAL.set(loginUserInfo);
        }
    }

    public static void clear() {
        THREAD_LOCAL.remove();
    }

    /**
     * 私有化构造函数
     */
    private UserContextHolder() {
    }

}
